<template>
  <div class="storage-order-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>入库单</h2>
      <el-button type="text" @click="handleBack">返回</el-button>
    </div>

    <!-- 查询与操作区域 -->
    <div class="search-action-bar">
      <el-input 
        v-model="searchKeyword" 
        placeholder="请输入关键字查询" 
        class="search-input"
        clearable
      />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="success" @click="handleAddOrder">新增入库单</el-button>
    </div>

    <!-- 入库单表格 -->
    <el-table 
      :data="filteredOrders" 
      border 
      stripe 
      class="order-table"
      v-loading="loading"
    >
      <el-table-column prop="time" label="时间" sortable />
      <el-table-column prop="orderNo" label="入库单编号" />
      <el-table-column prop="warehouse" label="仓库" />
      <el-table-column prop="operator" label="操作人" />
      <el-table-column prop="status" label="入库状态">
        <template #default="scope">
          <el-tag type="success">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleViewDetail(scope.row)"
          >
            明细
          </el-button>
          <el-button 
            type="warning" 
            size="small" 
            @click="handleEditOrder(scope.row)"
            v-if="scope.row.status !== '已完成'"
          >
            编辑
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDeleteOrder(scope.row.id)"
            v-if="scope.row.status !== '已完成'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination">
      <span class="total-info">共 {{ totalOrders }} 条 共 {{ totalPages }} 页</span>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="totalOrders"
        layout="prev, pager, next, jumper, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑入库单弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEditMode ? '编辑入库单' : '新增入库单'" 
      width="90%"
      :before-close="handleDialogClose"
    >
      <el-form 
        :model="formData" 
        ref="formRef" 
        :rules="formRules" 
        label-width="120px"
        class="order-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库时间" prop="time">
              <el-date-picker 
                v-model="formData.time" 
                type="date" 
                placeholder="选择入库时间" 
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单编号" prop="orderNo">
              <el-input 
                v-model="formData.orderNo" 
                placeholder="输入入库单编号" 
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouse">
              <el-select v-model="formData.warehouse" placeholder="选择仓库" clearable>
                <el-option 
                  v-for="item in warehouseOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作人" prop="operator">
              <el-input v-model="formData.operator" placeholder="输入操作人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库状态" prop="status">
              <el-select v-model="formData.status" placeholder="选择入库状态">
                <el-option label="已完成" value="已完成" />
                <el-option label="进行中" value="进行中" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 入库产品明细（修改部分） -->
        <el-form-item label="入库产品明细">
          <div class="detail-header" style="display: flex; align-items: center; margin-bottom: 10px;">
            <span style="font-weight: 500;">产品明细</span>
            <el-button 
              type="primary" 
              @click="addProduct"
              style="margin-left: 15px; background-color: #10b981; border-color: #10b981;"
            >
              <el-icon><Plus /></el-icon> 新增产品
            </el-button>
          </div>
          
          <el-table 
            :data="formData.productDetails" 
            border 
            stripe 
            class="detail-table"
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }"
          >
            <el-table-column label="序号" type="index"  />
            <el-table-column label="产品名称" >
              <template #default="scope">
                <el-input 
                  v-model="scope.row.productName" 
                  placeholder="请输入产品名称" 
                  style="width: 100%;"
                />
              </template>
            </el-table-column>
            <el-table-column label="产品编号" >
              <template #default="scope">
                <el-input 
                  v-model="scope.row.productNo" 
                  placeholder="请输入产品编号" 
                  style="width: 100%;"
                />
              </template>
            </el-table-column>
            <el-table-column label="规格" >
              <template #default="scope">
                <el-input 
                  v-model="scope.row.spec" 
                  placeholder="请输入规格" 
                  style="width: 100%;"
                />
              </template>
            </el-table-column>
            <el-table-column label="单位" >
              <template #default="scope">
                <el-input 
                  v-model="scope.row.unit" 
                  placeholder="个/件" 
                  style="width: 100%;"
                />
              </template>
            </el-table-column>
            <el-table-column label="采购价"  >
              <template #default="scope">
                <el-input 
                  v-model.number="scope.row.price" 
                  type="number" 
                  min="0" 
                  step="0.01" 
                  placeholder="0.00"
                  style="width: 100%;"
                />
              </template>
            </el-table-column>
            <el-table-column label="数量" width="150">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.quantity" 
                  :min="1" 
                  style="width: 100%;"
                  @change="calculateRowTotal(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="总金额"  >
              <template #default="scope">
                <el-input 
                  v-model="scope.row.totalAmount" 
                  placeholder="0.00" 
                  disabled
                  style="width: 100%; color: #10b981;"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" >
              <template #default="scope">
                <el-button 
                  type="danger" 
                  @click="removeProduct(scope.$index)"
                  icon="Delete"
                />
              </template>
            </el-table-column>
          </el-table>

          <!-- 合计信息 -->
          <div class="total-info" style="text-align: right; margin-top: 10px; padding: 10px; border-top: 1px solid #e5e7eb;">
            <span style="margin-right: 20px; font-weight: 500;">产品总数：{{ totalQuantity }}</span>
            <span style="font-weight: 500;">总金额：¥{{ totalAmount.toFixed(2) }}</span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSaveOrder"
        >
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 入库单明细弹窗 -->
    <el-dialog 
      v-model="detailVisible" 
      title="入库单明细" 
      width="800px"
    >
      <el-descriptions column="2" border>
        <el-descriptions-item label="入库时间">{{ currentOrder.time }}</el-descriptions-item>
        <el-descriptions-item label="入库单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{ currentOrder.warehouse }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ currentOrder.operator }}</el-descriptions-item>
        <el-descriptions-item label="入库状态">
          <el-tag 
            :type="currentOrder.status === '已完成' ? 'success' : 'info'"
          >
            {{ currentOrder.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ currentOrder.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="detail-table-container">
        <h3 class="detail-table-title">入库产品明细</h3>
        <el-table 
          :data="currentOrder.productDetails" 
          border 
          stripe 
          class="detail-table"
        >
          <el-table-column prop="productName" label="产品名称" />
          <el-table-column prop="productNo" label="产品编号" />
          <el-table-column prop="spec" label="规格" />
          <el-table-column prop="unit" label="单位" />
          <el-table-column prop="price" label="采购价" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="totalAmount" label="总金额" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog 
      v-model="deleteConfirmVisible" 
      title="确认删除" 
      width="300px"
    >
      <p>确定要删除此入库单吗？此操作不可撤销。</p>
      <template #footer>
        <el-button @click="deleteConfirmVisible = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="confirmDelete"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()

// 状态管理
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalOrders = ref(0)
const totalPages = ref(0)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const deleteConfirmVisible = ref(false)
const isEditMode = ref(false)
const currentOrder = ref({})
const deleteOrderId = ref(null)

// 表单引用
const formRef = ref(null)

// 表单数据（修改产品明细结构）
const formData = reactive({
  id: null,
  time: '',
  orderNo: '',
  warehouse: '',
  operator: '',
  status: '已完成',
  remark: '',
  productDetails: [
    { 
      productName: '', 
      productNo: '', 
      spec: '', 
      unit: '个', 
      price: 0, 
      quantity: 1,
      totalAmount: '0.00'
    }
  ]
})

// 计算总数量和总金额
const totalQuantity = computed(() => {
  return formData.productDetails.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

const totalAmount = computed(() => {
  return formData.productDetails.reduce((sum, item) => sum + Number(item.totalAmount || 0), 0)
})

// 表单验证规则（增强产品明细验证）
const formRules = {
  time: [{ required: true, message: '请选择入库时间', trigger: 'blur' }],
  orderNo: [{ required: true, message: '请输入入库单编号', trigger: 'blur' }],
  warehouse: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
  operator: [{ required: true, message: '请输入操作人', trigger: 'blur' }],
  productDetails: [{ 
    validator: (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('至少添加一个产品'))
      } else {
        // 验证每个产品的必填项
        for (const item of value) {
          if (!item.productName) {
            callback(new Error('产品名称不能为空'))
            return
          }
          if (!item.productNo) {
            callback(new Error('产品编号不能为空'))
            return
          }
          if (!item.quantity || item.quantity < 1) {
            callback(new Error('数量必须大于0'))
            return
          }
        }
        callback()
      }
    }, 
    trigger: 'blur' 
  }]
}

// 仓库下拉选项
const warehouseOptions = [
  { label: '001仓库', value: '001' },
  { label: '002仓库', value: '002' },
  { label: '003仓库', value: '003' },
  { label: '004仓库', value: '004' }
]

// 入库单数据（更新产品明细结构）
const storageOrders = reactive([
  {
    id: 1,
    time: '2022.05.22',
    orderNo: 'PD-20220517-00001',
    warehouse: '001',
    operator: '陈晨',
    status: '已完成',
    remark: '1号',
    productDetails: [
      { 
        productName: '丝芙兰精华', 
        productNo: 'SP001', 
        spec: '50ml',
        unit: '瓶',
        price: 120,
        quantity: 10,
        totalAmount: '1200.00'
      },
      { 
        productName: '兰蔻粉水', 
        productNo: 'LC002', 
        spec: '400ml',
        unit: '瓶',
        price: 350,
        quantity: 5,
        totalAmount: '1750.00'
      }
    ]
  },
  {
    id: 2,
    time: '2022.05.22',
    orderNo: 'PD-20220517-00002',
    warehouse: '002',
    operator: '陈光',
    status: '已完成',
    remark: '2号',
    productDetails: [
      { 
        productName: '雅诗兰黛小棕瓶', 
        productNo: 'YS003', 
        spec: '100ml',
        unit: '瓶',
        price: 980,
        quantity: 8,
        totalAmount: '7840.00'
      }
    ]
  }
])

// 过滤后的入库单
const filteredOrders = computed(() => {
  let result = storageOrders.filter(order => {
    const keyword = searchKeyword.value.toLowerCase()
    return (
      order.orderNo.toLowerCase().includes(keyword) ||
      order.warehouse.toLowerCase().includes(keyword) ||
      order.operator.toLowerCase().includes(keyword) ||
      order.status.toLowerCase().includes(keyword)
    )
  })

  totalOrders.value = result.length
  totalPages.value = Math.ceil(totalOrders.value / pageSize.value)

  const startIndex = (currentPage.value - 1) * pageSize.value
  return result.slice(startIndex, startIndex + pageSize.value)
})

// 初始化
onMounted(() => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
})

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 搜索事件
const handleSearch = () => {
  currentPage.value = 1
}

// 返回事件
const handleBack = () => {
  router.back()
}

// 新增入库单
const handleAddOrder = () => {
  isEditMode.value = false
  Object.assign(formData, {
    id: null,
    time: new Date().toISOString().split('T')[0],
    orderNo: '',
    warehouse: '',
    operator: '',
    status: '已完成',
    remark: '',
    productDetails: [
      { 
        productName: '', 
        productNo: '', 
        spec: '', 
        unit: '个', 
        price: 0, 
        quantity: 1,
        totalAmount: '0.00'
      }
    ]
  })
  dialogVisible.value = true
}

// 编辑入库单
const handleEditOrder = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 查看明细
const handleViewDetail = (row) => {
  currentOrder.value = { ...row }
  detailVisible.value = true
}

// 删除入库单
const handleDeleteOrder = (id) => {
  deleteOrderId.value = id
  deleteConfirmVisible.value = true
}

// 确认删除
const confirmDelete = () => {
  loading.value = true
  setTimeout(() => {
    const index = storageOrders.findIndex(order => order.id === deleteOrderId.value)
    if (index !== -1) {
      storageOrders.splice(index, 1)
    }
    deleteConfirmVisible.value = false
    loading.value = false
    ElMessage.success('入库单已删除')
  }, 500)
}

// 新增产品（修改为完整结构）
const addProduct = () => {
  formData.productDetails.push({
    productName: '',
    productNo: '',
    spec: '',
    unit: '个',
    price: 0,
    quantity: 1,
    totalAmount: '0.00'
  })
}

// 删除产品
const removeProduct = (index) => {
  if (formData.productDetails.length > 1) {
    formData.productDetails.splice(index, 1)
  } else {
    ElMessage.warning('至少保留一个产品')
  }
}

// 计算单行总金额
const calculateRowTotal = (row) => {
  if (row.price !== undefined && row.quantity !== undefined) {
    row.totalAmount = (row.price * row.quantity).toFixed(2)
  }
}

// 保存入库单
const handleSaveOrder = () => {
  if (!formRef.value) return

  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      setTimeout(() => {
        if (isEditMode.value) {
          const index = storageOrders.findIndex(order => order.id === formData.id)
          if (index !== -1) {
            storageOrders[index] = { ...formData }
          }
          ElMessage.success('入库单已更新')
        } else {
          const newId = Math.max(...storageOrders.map(o => o.id), 0) + 1
          const newOrder = {
            ...formData,
            id: newId,
            orderNo: `PD-${new Date().getFullYear()}${(new Date().getMonth() + 1).toString().padStart(2, '0')}${new Date().getDate().toString().padStart(2, '0')}-${newId.toString().padStart(4, '0')}`,
            time: new Date().toISOString().split('T')[0].replace(/-/g, '.')
          }
          storageOrders.unshift(newOrder)
          ElMessage.success('入库单已创建')
        }
        dialogVisible.value = false
        loading.value = false
      }, 500)
    }
  })
}

// 关闭弹窗
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogVisible.value = false
}
</script>

<style scoped>
.storage-order-page {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.search-action-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.order-table {
  width: 100%;
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.total-info {
  color: #606266;
  font-size: 14px;
}

.order-form {
  margin-top: 10px;
}

.detail-table-container {
  margin-top: 20px;
}

.detail-table-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}

.detail-table {
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-action-bar {
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
  }
}
</style>